package com.ruoyi.project.propertySystem.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.server.TreeSelectInspectItem;
import com.ruoyi.project.propertySystem.domain.*;
import com.ruoyi.project.propertySystem.domain.vo.InspectItemRecordVO;
import com.ruoyi.project.propertySystem.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.propertySystem.service.IInspectItemService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 巡检项主Service业务层处理
 * 
 * @author wangshuo
 * @date 2021-01-18
 */
@Service
public class InspectItemServiceImpl implements IInspectItemService 
{
    @Autowired
    private InspectItemMapper inspectItemMapper;
    @Autowired
    private InspectClassifyMapper inspectClassifyMapper;
    @Autowired
    private InspectFormworkMapper inspectFormworkMapper;
    @Autowired
    private InspectItemRecordMapper inspectItemRecordMapper;
    @Autowired
    private InspectRecordMapper inspectRecordMapper;
    @Autowired
    private ItemRecordPicMapper itemRecordPicMapper;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询巡检项主
     * 
     * @param id 巡检项主ID
     * @return 巡检项主
     */
    @Override
    public InspectItem selectInspectItemById(Long id)
    {
        return inspectItemMapper.selectInspectItemById(id);
    }

    /**
     * 查询巡检项主列表
     * 
     * @param inspectItem 巡检项主
     * @return 巡检项主
     */
    @Override
    public List<InspectItem> selectInspectItemList(InspectItem inspectItem)
    {
        return inspectItemMapper.selectInspectItemList(inspectItem);
    }

    /**
     * 新增巡检项主
     * 
     * @param inspectItem 巡检项主
     * @return 结果
     */
    @Override
    public int insertInspectItem(InspectItem inspectItem)
    {
        if(StringUtils.isBlank(inspectItem.getInspectView())){
            throw new BaseException("巡检结果设置不能为空");
        }
        inspectItem.setCreateBy(SecurityUtils.getUsername());
        inspectItem.setGmtModify(new Date());
        HashMap<String, Object> inspectView = new HashMap<>();
        inspectView.put("inspectView",inspectItem.getInspectView());
        String inspectViewSting = JSONObject.toJSONString(inspectView);
        inspectItem.setExtraField(inspectViewSting);
        int i = inspectItemMapper.insertInspectItem(inspectItem);
        String str = "I" + String.format("%06d", inspectItem.getId());
        inspectItem.setItemSn(str);
        inspectItemMapper.updateInspectItem(inspectItem);
        return i;
    }

    /**
     * 修改巡检项主
     * 
     * @param inspectItem 巡检项主
     * @return 结果
     */
    @Override
    public int updateInspectItem(InspectItem inspectItem)
    {
        if(StringUtils.isNotBlank(inspectItem.getInspectView())){
            HashMap<String, Object> inspectView = new HashMap<>();
            inspectView.put("inspectView", inspectItem.getInspectView());
            String inspectViewSting = JSONObject.toJSONString(inspectView);
            inspectItem.setExtraField(inspectViewSting);
        }
        return inspectItemMapper.updateInspectItem(inspectItem);
    }

    /**
     * 批量删除巡检项主
     * 
     * @param ids 需要删除的巡检项主ID
     * @return 结果
     */
    @Override
    public int deleteInspectItemByIds(Long[] ids)
    {
        return inspectItemMapper.deleteInspectItemByIds(ids);
    }

    /**
     * 删除巡检项主信息
     * 
     * @param id 巡检项主ID
     * @return 结果
     */
    @Override
    public int deleteInspectItemById(Long id)
    {
        return inspectItemMapper.deleteInspectItemById(id);
    }

    @Override
    public List<TreeSelectInspectItem> selectInspectItemTree(Long formworkId) {
        List<InspectClassify> inspectClassifies = inspectClassifyMapper.selectInspectClassifyList(new InspectClassify());
        return inspectClassifies.stream().map(x -> {
            TreeSelectInspectItem treeSelectInspectItem = new TreeSelectInspectItem();
            treeSelectInspectItem.setId(x.getClassifySn());
            treeSelectInspectItem.setLabel(x.getClassifyName());
            List<TreeSelectInspectItem> j = inspectItemMapper.selectInspectItemByClassifyId(x.getId()).stream().map(y -> {
                TreeSelectInspectItem treeSelectInspectItem2 = new TreeSelectInspectItem();
                treeSelectInspectItem2.setId(y.getItemSn());
                treeSelectInspectItem2.setLabel(y.getItemName());
                return treeSelectInspectItem2;
            }).collect(Collectors.toList());
            treeSelectInspectItem.setChildren(j);
            return treeSelectInspectItem;
        }).collect(Collectors.toList());
    }

    @Override
    public List<String> selectCheckItemByFormworkId(Long formworkId) {
        if(formworkId==null){
            return new ArrayList<>();
        }
        InspectFormwork inspectFormwork = new InspectFormwork();
        inspectFormwork.setFormworkId(formworkId);
        List<InspectFormwork> inspectFormworks = inspectFormworkMapper.selectInspectFormworkList(inspectFormwork);
        return inspectFormworks.stream().map(InspectFormwork::getItemSn).collect(Collectors.toList());
    }

    @Override
    public List<InspectItemRecordVO> getInspectItemsByClassifyAndRecordId(Long classifyId, Long inspectRecordId) {
        List<InspectItemRecordVO> inspectItemsByClassifyAndRecordId = inspectItemRecordMapper.getInspectItemsByClassifyAndRecordId(classifyId, inspectRecordId);
        inspectItemsByClassifyAndRecordId.forEach(x->{
            if(StringUtils.isNotBlank(x.getInspectView())){
                List<HashMap<String,Object>> strings = new ArrayList<>();
                List<String> strings1 = new ArrayList<>();
                String inspectView = x.getInspectView();
                String[] split = inspectView.split("，");
                for (String s : split) {
                    String[] split1 = s.split("\\|");
                    strings1.add(split1[0]);
                    strings1.add(split1[1]);
                }
                if(strings1.size()>0){
                    for (int i = 0; i < strings1.size(); i++) {
                        HashMap<String, Object> data = new HashMap<>();
                        data.put("value",i+"");
                        data.put("name",strings1.get(i));
                        strings.add(data);
                    }
                }
//                x.setPickerIndex(0);
            x.setPickerData(strings);
            }
            Long inspectItemRecordId = x.getInspectItemRecordId();
            ItemRecordPic itemRecordPic = new ItemRecordPic();
            itemRecordPic.setItemRecordId(inspectItemRecordId);
            List<ItemRecordPic> itemRecordPics = itemRecordPicMapper.selectItemRecordPicList(itemRecordPic);
            List<String> collect = itemRecordPics.stream().map(y-> serverConfig.getUrl()+y.getFilePath()).collect(Collectors.toList());
            x.setImgs(collect);
        });
        return inspectItemsByClassifyAndRecordId;
    }

    @Override
    @Transactional
    public int saveInspectItems(InspectItemRecordVO inspectItemRecordVO) {
    if(inspectItemRecordVO.getInspectItemRecordVOS().size()==0){
        throw new BaseException("保存结果参数异常");
    }
        try {
            inspectItemRecordVO.getInspectItemRecordVOS().forEach(x->{
                Long inspectItemRecordId = x.getInspectItemRecordId();
                ItemRecordPic itemRecordPic = new ItemRecordPic();
                itemRecordPic.setItemRecordId(inspectItemRecordId);
//                List<ItemRecordPic> itemRecordPics = itemRecordPicMapper.selectItemRecordPicList(itemRecordPic);
//                if(itemRecordPics.size()==0){
//                    throw new BaseException("请先上传图片");
//                }
                InspectItemRecord inspectItemRecord = new InspectItemRecord();
                inspectItemRecord.setId(x.getInspectItemRecordId());
                inspectItemRecord.setModifyBy(SecurityUtils.getUsername());
                inspectItemRecord.setGmtModify(new Date());
                inspectItemRecord.setRemark(x.getRemark());
                if(StringUtils.isNotBlank(x.getInspectView())){
                    if(x.getPickerIndex()!=null){
                        inspectItemRecord.setInspectResult(x.getPickerIndex());
                        inspectItemRecord.setStatus(1);
                    }else {
                        throw new BaseException("请勾选巡查结果");
                    }
                }else {
                    inspectItemRecord.setStatus(1);
                }
                inspectItemRecordMapper.updateInspectItemRecord(inspectItemRecord);
            });
            //判断所有的巡检项是否都已经巡检完成，完成则更新巡检记录的状态
            List<InspectItemRecord> inspectItemRecords =inspectItemRecordMapper.getUnInspectItemByRecordId(inspectItemRecordVO.getInspectRecordId());
            if(inspectItemRecords.size()==0){
                InspectRecord inspectRecord = new InspectRecord();
                inspectRecord.setId(inspectItemRecordVO.getInspectRecordId());
                inspectRecord.setStatus(1);
                inspectRecordMapper.updateInspectRecord(inspectRecord);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("保存失败,"+e.getMessage());
        }
    }
}
